<template>
  <div class="yu-input-wrapper">
    <slot name="prefix"></slot>
    <input
      :type="props.type"
      :class="inputClass"
      :value="modelValue"
      @input="inpInput"
      @change="inpChange"
      @focus="inpFocus"
      @blur="inpBlur"
      :placeholder="props.placeholder"
      :disabled="props.disabled"
      :readonly="props.readonly"
      :name="props.name"
    />
    <slot name="suffix"></slot>
    <yuicon v-if="props.clearable" name="clear" @click="handleClear" />
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'yu-input' })
import { reactive, withDefaults } from 'vue'
import yuicon from '../icon/YuIcon.vue'
const props = withDefaults(
  defineProps<{
    type?: string
    modelValue: string | number
    placeholder?: string | number
    disabled?: boolean
    readonly?: boolean
    name?: string
    clearable?: boolean
  }>(),
  {
    type: 'text',
    placeholder: '',
    disabled: false,
    readonly: false,
    name: '',
    clearable: false,
  }
)
const inputClass = reactive({
  'yu-input': true,
})
const emit = defineEmits(['update:modelValue', 'change', 'clear', 'focus', 'blur'])

const inpInput = (e) => {
  emit('update:modelValue', e.target.value)
}
const inpChange = (e) => {
  emit('change', e.target.value)
}
const handleClear = () => {
  emit('clear')
  emit('update:modelValue', '')
  emit('change', '')
}
const inpFocus = () => {
  emit('focus')
}
const inpBlur = () => {
  emit('blur')
}
</script>

<style scoped>
.yu-input-wrapper {
  display: inline-flex;
  align-items: center;
  gap: 0 5px;
  border: 1px solid #dcdfe6;
  border-radius: 3px;
  padding: 0 3px;
}
.yu-input-wrapper:focus-within {
  border: 1px solid #efada1;
}
.yu-input {
  border: none;
  border-radius: 3px;
  outline: none;
  height: 30px;
  font-size: 15px;
}
</style>